package org.techmore.activity;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.techmore.R;
import org.techmore.adapter.GalleryImageAdapter;
import org.techmore.utils.DownloadNoStoreHandler;
import org.techmore.utils.ImageDownloadHandler;
import org.techmore.utils.PropertiesUtil;
import org.techmore.utils.StringUtils;
import org.techmore.vo.StoreVO;
import org.techmore.zxing.client.android.CaptureActivity;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class CouponStoreDetailsActivity extends Activity {
	private ViewGroup linearLayout;
	private ArrayList<Bitmap> bitmapList = new ArrayList<Bitmap>();
	private StoreVO storeVO = new StoreVO();
	private SAXParserFactory factory = null;
	private SAXParser parser = null;
	private ViewGroup contentScrollView;
	private String serNo = null;
	
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setScreenOrientation();
        setContentScrollViewHeightDynamic();
        
        Intent intent = getIntent();
        serNo = intent.getStringExtra("serNo");
        doParseXML();
        addGotoListButtonListener();
        
        resetFooterLayout();
        controlVisiable();
    }
    
    /**
     * 設置屏幕方向
     */
    private void setScreenOrientation(){
    	getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);		//豎屏
//    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);		//橫屏
    }
    
    /**
     * 設置內容區
     */
    private void setContentScrollViewHeightDynamic(){
    	linearLayout = (ViewGroup)LayoutInflater.from(this).inflate(R.layout.techmore_d2, null);

        contentScrollView = (ScrollView) linearLayout.findViewById(R.id.contentScrollView);
        RelativeLayout titleRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.titleRelativeLayout);
        RelativeLayout footerRelativeLayout = (RelativeLayout) linearLayout.findViewById(R.id.footerRelativeLayout);
        
        LayoutParams contentLayoutParams = contentScrollView.getLayoutParams();
        
        //獲取屏幕高度
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer contentScrollViewHeight = displayMetrics.heightPixels;
        
        contentLayoutParams.height = contentScrollViewHeight - titleRelativeLayout.getLayoutParams().height - footerRelativeLayout.getLayoutParams().height - 40;
        
        contentScrollView.setLayoutParams(contentLayoutParams);
        
        setContentView(linearLayout);
    }
    
    private void addGotoListButtonListener(){
    	Button gotoListImageButton = (Button)findViewById(R.id.gotoListImageButton);
    	
    	gotoListImageButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(CouponStoreDetailsActivity.this, CouponMapActivity.class);
				CouponStoreDetailsActivity.this.startActivity(intent);
				CouponStoreDetailsActivity.this.finish();
			}
		});
    }
    
    private void resetFooterLayout(){
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        Integer windowWidth = displayMetrics.widthPixels;
        
    	LinearLayout couponListButton = (LinearLayout) linearLayout.findViewById(R.id.couponListButton);
        LinearLayout nearCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.nearCouponListButton);
    	LinearLayout myCouponListButton = (LinearLayout) linearLayout.findViewById(R.id.myCouponListButton);
    	LinearLayout couponScanner = (LinearLayout) linearLayout.findViewById(R.id.couponScanner);
    	
    	RelativeLayout.LayoutParams layoutParams = null;
    	
    	if(240<windowWidth){
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) nearCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		nearCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) myCouponListButton.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		myCouponListButton.setLayoutParams(layoutParams);
    		
    		layoutParams = (android.widget.RelativeLayout.LayoutParams) couponScanner.getLayoutParams();
    		layoutParams.setMargins((windowWidth-240)/5, 0, 0, 0 );
    		couponScanner.setLayoutParams(layoutParams);
    	}
    	
    	nearCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponStoreDetailsActivity.this, CouponMapActivity.class);
				CouponStoreDetailsActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    	couponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponStoreDetailsActivity.this, CouponListActivity.class);
				CouponStoreDetailsActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				MyCouponListActivity.this.finish();
				return false;
			}
		});
    	couponScanner.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(CouponStoreDetailsActivity.this);
				if(preferences.getBoolean("isLogin",false)){
					Intent intent = new Intent();
					intent.setClass(CouponStoreDetailsActivity.this, CaptureActivity.class);
					CouponStoreDetailsActivity.this.startActivity(intent);
					overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
				}else{
					CouponStoreDetailsActivity.this.startActivity(new Intent(CouponStoreDetailsActivity.this,CouponLoginActivity.class));
				}
				return false;
			}
		});
    	
    	myCouponListButton.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(CouponStoreDetailsActivity.this, MyCouponListActivity.class);
				CouponStoreDetailsActivity.this.startActivity(intent);
				overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//				CouponListActivity.this.finish();
				return false;
			}
		});
    	
    }
    
    private void fillGalleryData(){
    	bitmapList = new ArrayList<Bitmap>();
    	List<String> arrImageuri = new ArrayList<String>();
    	
    	ArrayList<String> imgUrlList = storeVO.getImgUrlList();
    	
    	for(String imgUrl : imgUrlList){
    		arrImageuri.add(imgUrl);	
    	}
    	
    	for(String imageuri : arrImageuri){
    		Handler imageHandler = new Handler(Looper.myLooper()){
    			@Override
    			public void handleMessage(Message msg) {
    				Gallery albumGallery = (Gallery) findViewById(R.id.A05_05_AlbumGallery);
    				
    				Bitmap bitmap = (Bitmap) msg.obj;
    				bitmapList.add(bitmap);
    		
    				albumGallery.setAdapter(new GalleryImageAdapter(CouponStoreDetailsActivity.this, bitmapList.toArray(new Bitmap[bitmapList.size()])));
    			}
    		};
    		
    		imageHandler.postDelayed(new ImageDownloadHandler(imageuri, imageHandler, imageuri.substring(imageuri.lastIndexOf("/"), imageuri.length())), 100);
    	}
    }
    
    /**
     * 填充數據
     */
    private void doParseXML(){
    	try {
			factory = SAXParserFactory.newInstance();
			parser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Log.e("ConsultCouponDetailsActivityDataHandler:", e.getMessage());
		}
    	
    	Handler dataHandler = null;
    	
    	String qrStoreDetailUrl = PropertiesUtil.getInstance().getValue("qr_store_detail_url");
		
    	qrStoreDetailUrl += "&serNo=" + serNo;
    	
    	dataHandler = new Handler(Looper.myLooper()){
    		public void handleMessage(android.os.Message msg) {
    			int sign = msg.what;
    			
    			if(sign == 1){
    				String uri = String.valueOf(msg.obj);
        			try {
        				ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(uri.getBytes());
        				Store_Handler store_Handler = new Store_Handler();
						parser.parse(byteArrayInputStream, store_Handler);
					} catch (SAXException e) {
						Log.e("D2ActivityDataHandler:SAXException", e.getMessage());
					} catch (IOException e) {
						Log.e("D2ActivityDataHandler:IOException", e.getMessage());
					}
					
					doFillContent();
    			}
    		}
    	};
    	
    	dataHandler.postDelayed(new DownloadNoStoreHandler(qrStoreDetailUrl, dataHandler, 1), 100);
    }
    
    private void doFillContent(){
    	ViewGroup contentScrollView = (ViewGroup)linearLayout.findViewById(R.id.contentScrollView);
    	
    	TextView txtsubject = (TextView)contentScrollView.findViewById(R.id.txtsubject);
    	TextView txtIntroduction = (TextView)contentScrollView.findViewById(R.id.txtIntroduction);
    	TextView txtOpenTime = (TextView)contentScrollView.findViewById(R.id.txtOpenTime);
    	TextView txtHoliday = (TextView)contentScrollView.findViewById(R.id.txtHoliday);
//    	Button btnRelateUrl = (Button)contentScrollView.findViewById(R.id.btnRelateUrl);
    	Button btnLiaisonTel = (Button)contentScrollView.findViewById(R.id.btnLiaisonTel);
    	Button btnLiaisonEmail = (Button)contentScrollView.findViewById(R.id.btnLiaisonEmail);
    	TextView txtLiaisonFax = (TextView)contentScrollView.findViewById(R.id.txtLiaisonFax);
    	
    	txtsubject.setText(storeVO.getSubject());
    	txtIntroduction.setText(storeVO.getIntroduction());
    	txtOpenTime.setText(storeVO.getOpenTime());
    	txtHoliday.setText(storeVO.getHoliday());
    	btnLiaisonTel.setText("電話:" + storeVO.getLiaisonTel());
    	btnLiaisonEmail.setText(storeVO.getLiaisonEmail());
    	txtLiaisonFax.setText("傳真:" + storeVO.getLiaisonFax());
    	
    	fillGalleryData();
    	adapterLiasionButton();
    }
    
    private void controlVisiable(){
    	ViewGroup lilayOpenTime = (ViewGroup)contentScrollView.findViewById(R.id.lilayOpenTime);
    	ViewGroup lilayHoliday = (ViewGroup)contentScrollView.findViewById(R.id.lilayHoliday);
    	Button btnRelateUrl = (Button)contentScrollView.findViewById(R.id.btnRelateUrl);
    	Button btnLiaisonTel = (Button)contentScrollView.findViewById(R.id.btnLiaisonTel);
    	Button btnLiaisonEmail = (Button)contentScrollView.findViewById(R.id.btnLiaisonEmail);
    	ViewGroup reLayLiaisonFax = (ViewGroup)contentScrollView.findViewById(R.id.reLayLiaisonFax);
    	
    	String openTime = storeVO.getOpenTime();
    	String holiday = storeVO.getHoliday();
    	String url = storeVO.getRelateUrl();
    	String tel = storeVO.getLiaisonTel();
    	String email = storeVO.getLiaisonEmail();
    	String fax = storeVO.getLiaisonFax();
    	
    	if(StringUtils.isEmpty(openTime)){
    		lilayOpenTime.setVisibility(View.GONE);
    	}
    	if(StringUtils.isEmpty(holiday)){
    		lilayHoliday.setVisibility(View.GONE);
    	}
    	if(StringUtils.isEmpty(url)){
    		btnRelateUrl.setVisibility(View.GONE);
    	}
    	if(StringUtils.isEmpty(tel)){
    		btnLiaisonTel.setVisibility(View.GONE);
    	}
    	if(StringUtils.isEmpty(email)){
    		btnLiaisonEmail.setVisibility(View.GONE);
    	}
    	if(StringUtils.isEmpty(fax)){
    		reLayLiaisonFax.setVisibility(View.GONE);
    	}
    }
    
    private void adapterLiasionButton(){
    	Button btnRelateUrl = (Button)contentScrollView.findViewById(R.id.btnRelateUrl);
    	Button btnLiaisonTel = (Button)contentScrollView.findViewById(R.id.btnLiaisonTel);
    	Button btnLiaisonEmail = (Button)contentScrollView.findViewById(R.id.btnLiaisonEmail);
    	
    	final String url = storeVO.getRelateUrl();
    	final String tel = storeVO.getLiaisonTel();
    	final String email = storeVO.getLiaisonEmail();
    	
    	btnRelateUrl.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Uri uri = Uri.parse(url);
				Intent it  = new Intent(Intent.ACTION_VIEW,uri);
				startActivity(it);	
			}
		});
    		
    	btnLiaisonTel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(StringUtils.isNotEmpty(tel)){
					tel.replace("-", "");
					tel.replace(" ", "");
					
					Uri uri = Uri.parse("tel:" + tel);
					Intent it = new Intent(Intent.ACTION_DIAL, uri); 
					startActivity(it);	
				}
			}
		});
    	
    	btnLiaisonEmail.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(StringUtils.isNotEmpty(email)){
					Uri uri = Uri.parse("mailto:" + email);
					Intent it = new Intent(Intent.ACTION_SENDTO, uri);
					startActivity(it);	
				}
			}
		});
    }
    
    
    
    public class Store_Handler extends DefaultHandler{
		public Store_Handler(){}
		
		@Override
		public void startDocument() throws SAXException {
			super.startDocument();
		}
		
		@Override
		public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
			super.startElement(uri, localName, qName, attributes);
			
			if("LBSStoreAdvDeatil ".equals(qName) || "LBSStoreAdvDeatil".equals(localName) ){
				storeVO.setSerNo(attributes.getValue("serNo"));
				storeVO.setSubject(attributes.getValue("subject"));
				storeVO.setLongitude(attributes.getValue("longitude"));
				storeVO.setLatitude(attributes.getValue("latitude"));
				storeVO.setMapIconUrl(attributes.getValue("mapIconUrl"));
				storeVO.setIntroduction(attributes.getValue("introduction"));
				storeVO.setOpenTime(attributes.getValue("openTime"));
				storeVO.setHoliday(attributes.getValue("holiday"));
				storeVO.setRelateUrl(attributes.getValue("relateUrl"));
				storeVO.setLiaisonTel(attributes.getValue("liaisonTel"));
				storeVO.setLiaisonFax(attributes.getValue("liaisonFax"));
				storeVO.setLiaisonEmail(attributes.getValue("liaisonEmail"));
			}
			
			if("storeImg".equals(qName) || "storeImg".equals(localName) ){
				for(String alphabet : StringUtils.getAlphabetList()){
					String imgUrl = attributes.getValue("img" + alphabet + "Url");
					
					if(StringUtils.isNotEmpty(imgUrl)){
						storeVO.getImgUrlList().add(imgUrl);	
					}
				}
			}
		}
		
		@Override
		public void endDocument() throws SAXException {
			super.endDocument();
		}
		
		@Override
		public void endElement(String uri, String localName, String qName) throws SAXException {
			super.endElement(uri, localName, qName);
			if("LBSStoreAdvDeatil".equals(qName) || "LBSStoreAdvDeatil".equals(localName)){
			}
		}
		
		@Override
		public void characters(char[] ch, int start, int length) throws SAXException {
		}
	}
}